package com.navicoa.e_libreria.utiles;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

//Patron: Singleton

public class AdministradorConexion {
	
	private static AdministradorConexion ac = null;
	private static Properties propiedades = new Properties();
	private Driver dbDriver = null;
	
	private AdministradorConexion(){
		try{
			InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("dbconfiguration.properties");
			propiedades.load(is);
		} 
		catch (Exception e1){
			System.err.println("El fichero de propiedades de la BDs no se ha encontrado");
			e1.printStackTrace();
		}
		
		try{
			String driverName =  propiedades.getProperty("driverName");
			dbDriver = (Driver) Class.forName(driverName).newInstance();
	        DriverManager.registerDriver(dbDriver);
		} 
		catch (Exception e){
			System.err.println("Unable to register JDBC Driver");
	        e.printStackTrace();
		}
	}

	public static synchronized AdministradorConexion getAdministrador(){
		if(ac == null){
			ac = new AdministradorConexion();
		}
		
		return ac;
	}
	
	public Connection checkOut() {
        Connection conn = null;

        try {
        	String uri = propiedades.getProperty("dBUri");
        	String user = propiedades.getProperty("username");
        	String passwd  = propiedades.getProperty("password");
            conn = DriverManager.getConnection(uri,user ,passwd);
        } catch (Exception e) {
            System.err.println("Unable to open a new JDBC connection");
            e.printStackTrace();
        }

        return conn;
    }

    public void checkIn(Connection conn) {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    protected void finalize() {
        try {
            DriverManager.deregisterDriver(dbDriver);
        } catch (SQLException e) {
            System.err.println("Unable to deregister JDBC driver");
            e.printStackTrace();
        }

    }
}
